import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

import 'report_controller.dart';
import '../../../../common/models/index.dart';

class ReportPage extends StatelessWidget {
  const ReportPage({super.key});

  @override
  Widget build(BuildContext context) {
    // 初始化控制器
    final controller = Get.put(ReportController());
    
    return Scaffold(
      backgroundColor: Colors.grey[50],
      appBar: AppBar(
        leading: IconButton(
          onPressed: () {
            Get.back();
          },
          icon: const Icon(Icons.arrow_back_ios_new_outlined, color: Colors.black),
        ),
        title: const Text("举报信息"),
        centerTitle: true,
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 0,
        systemOverlayStyle: const SystemUiOverlayStyle(
          statusBarColor: Colors.transparent,
          statusBarIconBrightness: Brightness.dark,
        ),
      ),
      body: Obx(() {
        // 显示加载状态
        if (controller.isLoading.value && controller.reportList.isEmpty) {
          return const Center(
            child: CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFCB5050)),
            ),
          );
        }

        // 显示空状态
        if (controller.shouldShowEmptyState) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  controller.hasError.value ? Icons.error_outline : Icons.report_outlined,
                  size: 64,
                  color: Colors.grey[400],
                ),
                const SizedBox(height: 16),
                Text(
                  controller.emptyStateText,
                  style: TextStyle(
                    fontSize: 16,
                    color: Colors.grey[600],
                  ),
                ),
                if (controller.hasError.value) ...[
                  const SizedBox(height: 16),
                  ElevatedButton(
                    onPressed: controller.retryLoad,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color(0xFFCB5050),
                      foregroundColor: Colors.white,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                    ),
                    child: const Text('重试'),
                  ),
                ],
              ],
            ),
          );
        }

        // 显示举报列表
        return RefreshIndicator(
          onRefresh: controller.refreshData,
          color: const Color(0xFFCB5050),
          child: NotificationListener<ScrollNotification>(
            onNotification: (ScrollNotification scrollInfo) {
              if (scrollInfo.metrics.pixels == scrollInfo.metrics.maxScrollExtent) {
                // 触底加载更多
                if (controller.hasMoreData.value && !controller.isLoadingMore.value) {
                  controller.loadMoreData();
                }
              }
              return false;
            },
            child: ListView.builder(
              padding: const EdgeInsets.all(16),
              itemCount: controller.reportList.length + (controller.reportList.isNotEmpty ? 1 : 0),
              itemBuilder: (context, index) {
                if (index == controller.reportList.length) {
                  // 显示加载更多指示器
                  return _buildLoadMoreIndicator(controller);
                }
                final report = controller.reportList[index];
                return _buildReportItem(report, controller);
              },
            ),
          ),
        );
      }),
    );
  }

  /// 构建加载更多指示器
  Widget _buildLoadMoreIndicator(ReportController controller) {
    return Obx(() {
      if (controller.isLoadingMore.value) {
        return Container(
          height: 55.0,
          alignment: Alignment.center,
          child: const CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFCB5050)),
          ),
        );
      } else if (!controller.hasMoreData.value) {
        return Container(
          height: 55.0,
          alignment: Alignment.center,
          child: const Text(
            "没有更多数据了!",
            style: TextStyle(
              color: Colors.grey,
              fontSize: 14,
            ),
          ),
        );
      } else {
        return Container(
          height: 55.0,
          alignment: Alignment.center,
          child: const Text(
            "上拉加载更多",
            style: TextStyle(
              color: Colors.grey,
              fontSize: 14,
            ),
          ),
        );
      }
    });
  }

  /// 构建举报项目卡片
  Widget _buildReportItem(ReportItem report, ReportController controller) {
    final statusDisplay = controller.getReportStatusDisplay(report);
    final statusColor = _getStatusColor(statusDisplay['color']);

    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 头部：举报类型和状态
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  controller.getReportTypeDisplay(report.reportType),
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Colors.black87,
                  ),
                ),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: statusColor.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(6),
                    border: Border.all(color: statusColor.withOpacity(0.3)),
                  ),
                  child: Text(
                    statusDisplay['text'],
                    style: TextStyle(
                      fontSize: 12,
                      color: statusColor,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ],
            ),
            
            const SizedBox(height: 12),
            
            // 举报原因
            Text(
              '举报原因：${report.reportReason ?? '未知'}',
              style: const TextStyle(
                fontSize: 14,
                color: Colors.black87,
                fontWeight: FontWeight.w500,
              ),
            ),
            
            // 详细描述（如果有）
            if (report.extraData?['description'] != null) ...[
              const SizedBox(height: 8),
              Text(
                report.extraData!['description'].toString(),
                style: TextStyle(
                  fontSize: 13,
                  color: Colors.grey[600],
                  height: 1.4,
                ),
                maxLines: 3,
                overflow: TextOverflow.ellipsis,
              ),
            ],
            
            const SizedBox(height: 12),
            
            // 底部信息
            Row(
              children: [
                Icon(
                  Icons.access_time,
                  size: 14,
                  color: Colors.grey[500],
                ),
                const SizedBox(width: 4),
                Text(
                  controller.formatReportTime(report.reportTime ?? report.createdAt),
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[500],
                  ),
                ),
                
                if (report.reportId != null) ...[
                  const SizedBox(width: 16),
                  Icon(
                    Icons.tag,
                    size: 14,
                    color: Colors.grey[500],
                  ),
                  const SizedBox(width: 4),
                  Text(
                    'ID: ${report.reportId}',
                    style: TextStyle(
                      fontSize: 12,
                      color: Colors.grey[500],
                    ),
                  ),
                ],
              ],
            ),
            
            // 处理结果（如果已处理）
            if (report.isProcessed && report.processResult != null) ...[
              const SizedBox(height: 12),
              Container(
                width: double.infinity,
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.green.withOpacity(0.05),
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: Colors.green.withOpacity(0.2)),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '处理结果',
                      style: TextStyle(
                        fontSize: 13,
                        fontWeight: FontWeight.w600,
                        color: Colors.green[700],
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      report.processResult.toString(),
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.green[600],
                        height: 1.3,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }

  /// 获取状态颜色
  Color _getStatusColor(String colorName) {
    switch (colorName) {
      case 'orange':
        return Colors.orange;
      case 'blue':
        return Colors.blue;
      case 'green':
        return Colors.green;
      case 'red':
        return Colors.red;
      default:
        return Colors.grey;
    }
  }
}

